<script lang="ts" setup>
import type {
  GridInstance as VxeGridInstance,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';

import { computed, onMounted, ref } from 'vue';

import { Button, Form, Input, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getLogListApi } from '#/api/core/log';

// 查询参数
const queryParams = ref({
  username: '',
  current_page: 1,
});

// 表格引用
const gridRef = ref<VxeGridInstance>();

interface LogData {
  id: number;
  content: string;
  create_time: string;
  type: string;
  username: string;
  current_page: number;
  total_page: number;
}

// 存储表格数据
const tableData = ref<LogData[]>([]);

// 添加分页相关的 ref
const currentPage = ref(1);
const totalPage = ref(0);

// 表格配置
const gridOptions = computed<VxeGridProps<LogData>>(() => ({
  columns: [
    { field: 'id', title: 'ID', width: 80 },
    { field: 'type', title: '操作类型', width: 120 },
    { field: 'content', title: '内容', minWidth: 200 },
    { field: 'username', title: '用户名', width: 120 },
    { field: 'create_time', title: '创建时间', width: 180 },
  ],
  data: tableData.value,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    total: totalPage.value * 10,
    currentPage: currentPage.value,
    layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total'],
    perfect: true,
  },
  sortConfig: {
    multiple: true,
  },
}));

const gridEvents: VxeGridListeners<LogData> = {
  pageChange: ({ currentPage: newPage }) => {
    currentPage.value = newPage;
    loadData();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions: gridOptions.value,
});

// 加载数据方法
async function loadData() {
  try {
    gridApi.setLoading(true);
    const params = {
      username: queryParams.value.username,
      current_page: currentPage.value,
      page_size: gridOptions.value.pagerConfig?.pageSize || 10,
    };
    const data = await getLogListApi(params);

    if (Array.isArray(data) && data.length > 0) {
      tableData.value = data;
      const total_page = data[0]?.total_page || 0;
      totalPage.value = total_page;

      gridApi.setGridOptions({
        data: tableData.value,
        pagerConfig: {
          ...gridOptions.value.pagerConfig,
          total: total_page * 10,
          currentPage: currentPage.value,
        },
      });
    } else {
      tableData.value = [];
    }
  } catch {
    message.error('获取日志列表失败');
    tableData.value = [];
  } finally {
    gridApi.setLoading(false);
  }
}

onMounted(() => {
  loadData();
});

// 搜索方法
function handleSearch() {
  currentPage.value = 1; // 搜索时重置到第一页
  loadData();
}

// 重置方法
function handleReset() {
  currentPage.value = 1; // 重置时回到第一页
  queryParams.value.username = '';
  loadData();
}

// 刷新方法
function handleRefresh() {
  loadData();
}
</script>

<template>
  <div class="vp-raw w-full">
    <Grid ref="gridRef">
      <template #toolbar-tools>
        <Form :model="queryParams" layout="inline">
          <Form.Item>
            <Input
              v-model:value="queryParams.username"
              allow-clear
              placeholder="请输入用户名搜索"
              @press-enter="handleSearch"
            />
          </Form.Item>
          <Form.Item>
            <Button class="mr-2" type="primary" @click="handleSearch">
              搜索
            </Button>
            <Button class="mr-2" @click="handleReset"> 重置 </Button>
            <Button type="primary" @click="handleRefresh"> 刷新 </Button>
          </Form.Item>
        </Form>
      </template>
    </Grid>
  </div>
</template>
